import {queryMenu, addMenu, delMenu, putMenu, getMenu} from '../services/menu';

export default {
  namespace: 'menu',
  state: {
    data: [],
    formValues: {},
  },

  effects: {
    * fetch({payload}, {call, put}) {
      const response = yield call(queryMenu, payload);
      if (response) {
        yield put({
          type: 'save',
          payload: response,
        });
      }
    },
    * add({payload, callback}, {call, put}) {
      const response = yield call(addMenu, payload);
      if (response && response.code === 0) {
        const data = yield call(queryMenu, payload);
        if (data) {
          yield put({
            type: 'save',
            payload: data,
          });
        }
        if (callback) callback()
      }
    },
    * new({payload, callback}, {put}) {
      yield put({
        type: 'saveFormValue',
        payload: payload,
      });
      if (callback) callback()
    },
    * get({payload, callback}, {call, put}) {
      const response = yield call(getMenu, payload);
      if (response) {
        yield put({
          type: 'saveFormValue',
          payload: response,
        });
        if (callback) callback()
      }
    },
    * change({payload}, {put}) {
      yield put({
        type: 'changeFormValue',
        payload: payload,
      });
    },
    * edit({payload, callback}, {call, put}) {
      const response = yield call(putMenu, payload);
      if (response && response.code === 0) {
        yield put({
          type: 'saveFormValue',
          payload: payload,
        });
        const data = yield call(queryMenu, payload);
        if (data) {
          yield put({
            type: 'save',
            payload: data,
          });
        }
        if (callback) callback()

      }
    },
    * remove({payload, callback}, {call, put}) {
      const response = yield call(delMenu, payload.id);
      if (response && response.code === 0) {
        const data = yield call(queryMenu, payload);
        if (data) {
          yield put({
            type: 'save',
            payload: data,
          });
        }
        if (callback) callback()
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload,
      };
    },
    changeFormValue(state, action) {
      return {
        ...state,
        formValues: {...state.formValues, ...action.payload},
      };
    },
    saveFormValue(state, action) {
      return {
        ...state,
        formValues: action.payload,
      };
    },
  },
};
